package cn.xo68.boot.webgather.resolve;

import cn.xo68.boot.webgather.http.HttpClient;
import cn.xo68.boot.webgather.http.StringHttpCallback;
import cn.xo68.boot.webgather.resolve.htmlunit.GatherExecutor;
import com.gargoylesoftware.htmlunit.WebRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * 解析器工厂
 */
public class ResolveFactory {

    private final static Logger logger = LoggerFactory.getLogger(ResolveFactory.class);

    private final GatherExecutor gatherExecutor;

    public ResolveFactory(GatherExecutor gatherExecutor) {
        this.gatherExecutor = gatherExecutor;
    }

    public ContentResolve getContentResolve(ResolveTypeEnums resolveTypeEnums, String urlStr) {
        ContentResolveDefaultImpl contentResolveDefault=new ContentResolveDefaultImpl();

        switch (resolveTypeEnums){
            case HTML_UNIT:
                URL url=null;
                try {
                    logger.info("内容地址：{}", urlStr);
                    url=new URL(urlStr);
                } catch (MalformedURLException e) {
                    logger.error("请求地址不规范", e);
                    break;
                }
                WebRequest webRequest=new WebRequest(url);
                gatherExecutor.execute(webRequest, contentResolveDefault);
                break;
            case OK_HTTP:
                StringHttpCallback stringHttpCallback = new StringHttpCallback();
                // 服务端获取最新版本号
                HttpClient.getInstance().get(urlStr, null, stringHttpCallback);
                if(stringHttpCallback.hasException()){
                    //throw stringHttpCallback.getException();
                    throw new RuntimeException("",stringHttpCallback.getException());
                }else {
                    contentResolveDefault.setDocument(stringHttpCallback.getResult());
                }
                break;
        }

        return contentResolveDefault;
    }
}
